package com.orange.common.helper

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.LogUtils
import com.orange.common.ComConstants
import com.orange.common.data.User
import com.orange.common.util.MMKVUtils

/**
 * Created by Orange on 2022/11/15 20:23.
 */
object UserHelper {

    var user: User = User()
        private set

    private val _userLiveData = MutableLiveData(user)
    val userLiveData: LiveData<User> = _userLiveData

    /**
     * 加载本地用户信息
     */
    fun loadLocalUser() {
        val localUser = MMKVUtils.getAny<User>(ComConstants.LOCAL_USER)
        localUser?.let {
            LogUtils.d("加载本地用户信息 $it")
            user = it
            _userLiveData.value = it
        }
    }

    /**
     * 保存登录信息
     */
    fun saveLoginInfo(newUser: User) {
        newUser.let {
            val result = MMKVUtils.put(ComConstants.LOCAL_USER, it)
            if (result) {
                LogUtils.d("保存登录信息 $it")
                user = it
                _userLiveData.value = it
            }
        }
    }

    /**
     * 保存用户信息
     */
    fun saveUser(newUser: User) {
        val copyUser = newUser.copy(
            token = user.token
        )
        saveLoginInfo(copyUser)
    }

    /**
     * 是否登录
     */
    fun isLogin(): Boolean = user.token.isNotEmpty()

    /**
     * 是否是游客
     */
    fun isGuest(): Boolean {
        return user.is_guest == 1
    }

    /**
     * 更新token
     */
    fun updateToken(token:String) {
        user.token = token
        saveLoginInfo(user)
    }
}